/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package util.enums;

import util.StringUtil;

/**
 *
 * @author Rdelacruz
 */
public class EnumUtil {
     //http://stackoverflow.com/questions/6768905/get-enum-instance-from-class-extends-enum-using-string-value
    public static <T extends Enum<T>> T getEnumByLiteral(final Class<T> enumClass, final String literal) {
        if(!StringUtil.esVacioONulo(literal))
            return Enum.valueOf(enumClass, literal);
        return null;
    }
   
    //http://stackoverflow.com/questions/2205891/iterate-enum-values-using-java-generics
    //http://stackoverflow.com/questions/11909579/enum-extends-interface
    public static <T extends Enum<T> & CodigoInt> T getEnumByCodigo(final Class<T> enumClass, final Integer codigo) {
        if(codigo!=null) {
            int codigoInt = codigo;
            for(T e : enumClass.getEnumConstants()) {            
                if(e.getCodigo()==codigoInt)
                    return e;
            }
        }
        return null;
    } 
    
    
    public static <T extends Enum<T> & CodigoString> T getEnumByCodigo(final Class<T> enumClass, final String codigo) {
        if(!StringUtil.esVacioONulo(codigo)) {
            for(T e : enumClass.getEnumConstants()) {            
                if(e.getCodigo().equals(codigo))
                    return e;
            }
        }
        return null;
    }

    public static <T extends Enum<T> & CodigoString> String getCodigoString(final Class<T> enumClass, T e) {
        return e!=null ? e.getCodigo() : null;
    }
    
    public static <T extends Enum<T> & CodigoInt> Integer getCodigoIntEnum(final Class<T> enumClass, T e) {
        return e!=null ? e.getCodigo() : null;
    }

    public static String getLiteral(Enum e) {
        return e!=null ? e.name() : null;
    }
}
